<?php

namespace App\Http\Controllers\Admin;

use App\Models\Dictionary;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class DictionaryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        $keyword=$request->input('keyword','');
        $query=Dictionary::select()->with(['child'=>function($query){
            $query->select()->with(['child'=>function($query){
                $query->select()->get();
            }])->get();
        }])->where(['pid'=>0]);
        if($keyword!=''){
            $query->where(function ($query)use ($keyword){
               $query->where('name','like',"%$keyword%")
                   ->orWhere('intro','like',"%$keyword%")
                   ->orWhere(function ($query) use ($keyword){
                       $query->whereHas('child',function ($query) use ($keyword){
                           $query->where('name','like',"%$keyword%")->orWhere(function ($query) use ($keyword){
                               $query->whereHas('child',function ($query) use ($keyword){
                                   $query->where('name','like',"%$keyword%");
                               }) ;
                           });
                       });
               });
            });
        }
        $dictionaries=$query->paginate();
        $dictionaries->appends(['keyword'=>$keyword]);
        $dictionaries->keyword=$keyword;
        return view('Admin.Dictionary.index',compact('dictionaries'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('Admin.Dictionary.create');

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'name'=>'required|unique:dictionaries',
//            'child'=>'required'
        ],[
            'name.required'=>'请填写配置项',
            'name.unique'=>'该配置项已存在',
            'child.required'=>'请填写值'
        ]);
        DB::beginTransaction();
        try{
            $model=Dictionary::create(['name'=>$request->name,'intro'=>$request->intro,'pid'=>0]);
            if($request->child){
                foreach ($request->child as $child){
                    $model_second=Dictionary::create(['name'=>$child['name'],'pid'=>$model->id]);
                    if(isset($child['child']) && count($child['child'])){
                        foreach ($child['child'] as $item){
                            Dictionary::create(['name'=>$item,'pid'=>$model_second->id]);
                        }
                    }
                }
            }
            DB::commit();
            return response()->json(['status'=>200,'msg'=>'添加成功']);
        }catch (\Exception $e){
            DB::rollback();
            return response()->json(['status'=>201,'msg'=>'添加失败:'.$e->getMessage()]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $dictionary=Dictionary::select()->with(['child'=>function($query){
            $query->select()->with(['child'=>function($query){
                $query->select()->get();
            }])->get();
        }])->where(['pid'=>0,'id'=>$id])->first();
        if($dictionary==null){
            abort(404);
        }
        return view('Admin.Dictionary.edit',compact('dictionary'));

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'name'=>'required|unique:dictionaries,name,'.$id,
//            'child'=>'required'
        ],[
            'name.required'=>'请填写配置项',
            'name.unique'=>'该配置项已存在',
            'child.required'=>'请填写值'
        ]);
        DB::beginTransaction();
        try{
            $model=Dictionary::updateOrCreate(['name'=>$request->name,'intro'=>$request->intro],['id'=>$id]);
            if($request->child){
                foreach ($request->child as $key=>$child){
                    $model_second=Dictionary::where(['pid'=>$model->id,'id'=>$key])->first();
                    if($model_second!=null){
                        $model_second->name=$child['name'];
                        $model_second->save();
                    }else{
                        $model_second=Dictionary::create(['name'=>$child['name'],'pid'=>$model->id]);
                    }
                    if(isset($child['child']) && count($child['child'])){
                        foreach ($child['child'] as $key2=>$item){
                            $model_third=Dictionary::where(['pid'=>$model_second->id,'id'=>$key2])->first();
                            if($model_third!=null){
                                $model_third->name=$item;
                                $model_third->save();
                            }else{
                                Dictionary::create(['name'=>$item,'pid'=>$model_second->id]);
                            }
                        }
                    }
                }
            }
            DB::commit();
            return response()->json(['status'=>200,'msg'=>'修改成功']);
        }catch (\Exception $e){
            DB::rollaback();
            return response()->json(['status'=>201,'msg'=>'修改失败:'.$e->getMessage()]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
